export const deg2rad = (deg) => {
  return deg * (Math.PI / 180);
};

export const getDistanceFromLatLonInKm = (lat1, lon1, lat2, lon2) => {
  const R = 6371; // 地球半径，单位为千米
  const dLat = deg2rad(lat2 - lat1); // deg2rad 角度转弧度
  const dLon = deg2rad(lon2 - lon1);
  const a =
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(deg2rad(lat1)) *
      Math.cos(deg2rad(lat2)) *
      Math.sin(dLon / 2) *
      Math.sin(dLon / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  const distance = R * c; // 距离，单位为千米
  return distance;
};

export const getdistence = (lat1, lng1, lat2, lng2) => {
  const r = getDistanceFromLatLonInKm(lat1, lng1, lat2, lng2);
  if (r > 1) {
    return r.toFixed(2) + "公里";
  } else {
    return (r * 1000).toFixed(2) + "米";
  }
};

export const debounce = (func, wait) => {
  let timeout;

  return function (...args) {
    const context = this;
    if (timeout) {
      clearTimeout(timeout);
      timeout = null;
    }
    timeout = setTimeout(() => func.apply(context, args), wait);
  };
};
